/*
 *所有关于zm_data_record_auditing类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*zm_data_record_auditingService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using VOL.AppManager.IRepositories;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using VOL.Entity.ResDto;
using VOL.Entity.新文件夹;

namespace VOL.AppManager.Services
{
    public partial class zm_data_record_auditingService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Izm_data_record_auditingRepository _repository;//访问数据库
        WebResponseContent webResponse = new WebResponseContent();
        [ActivatorUtilitiesConstructor]
        public zm_data_record_auditingService(
            Izm_data_record_auditingRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }


        public PageGridData<zmdatarecordauditingdto> GetData(zmdatarecordauditingQuery options)
        {
            DynamicParameters sqlParams = new DynamicParameters();

            string sql = "   select row_number() OVER () AS idx,  * ,case when shzt is null then '未审核' when shzt=0 then '不通过'  when shzt=1 then '已通过' end shztname from ( select  create_name, sqcs ,b.id,a.id as data_id,a.projectname,jycs, case when xxtj_state =0 then '未交验' when xxtj_state=1 then '已交验'   end xxtj_state,shzt,case when accept_state =3 then '正在验收中' when accept_state=0  then '不通过'  when accept_state=1 then '已通过' else '未开始验收' end accept_state,TO_CHAR(xxtj_time,'YYYY-MM-DD HH24:MI:ss') xxtj_time ,TO_CHAR(create_time, 'YYYY-MM-DD HH24:MI:ss')create_time,TO_CHAR(sh_time, 'YYYY-MM-DD HH24:MI:ss') sh_time ,TO_CHAR(startdate, 'YYYY-MM-DD HH24:MI:ss') startdate,TO_CHAR(yjfkdate, 'YYYY-MM-DD HH24:MI:ss') yjfkdate,TO_CHAR(enddate, 'YYYY-MM-DD HH24:MI:ss') enddate,sh_name ,a.xzqdm,a.xzqname,a.provmc,a.provcode,a.citydm,a.citymc ,\"WorkUnit\",\"UserTrueName\" from (select t1.*,\"WorkUnit\",\"UserTrueName\" from zm_data_record t1 left join sys_user t2 on t1.userid::integer  =t2.\"User_Id\") a left  join   zm_data_record_auditing b on a.id=b.data_id where 1=1 and a.submit_state='1'  order by sh_time desc,a.create_time desc  ) t where 1=1  ";
            string sqlcount = "    select  count(1)  from zm_data_record a left  join   zm_data_record_auditing b on a.id=b.data_id where 1=1 and  a.submit_state='1'";

            if (options.sq_sj != null && options.sq_sj.Count == 2)
            {
                var start_time = Convert.ToDateTime(options.sq_sj[0] + "").ToString("yyyy-MM-dd") + "";
                var end_time = Convert.ToDateTime(options.sq_sj[1] + "").ToString("yyyy-MM-dd") + "";
                sqlcount += " and date(a.create_time) between '" + start_time + " 00:00:00' and '" + end_time + "  23:59:59'  ";
                sql += " and date(create_time) between '" + start_time + " 00:00:00' and '" + end_time + " 23:59:59'  ";

            }
            if (options.sh_sj != null && options.sh_sj.Count == 2)
            {
                var start_time = Convert.ToDateTime(options.sh_sj[0] + "").ToString("yyyy-MM-dd") + "";
                var end_time = Convert.ToDateTime(options.sh_sj[1] + "").ToString("yyyy-MM-dd") + "";
                sqlcount += " and date(sh_time)  between '" + start_time + " 00:00:00' and '" + end_time + "  23:59:59'  ";
                sql += " and date(sh_time)  between '" + start_time + " 00:00:00' and '" + end_time + "  23:59:59'  ";
            }
            if (options.shzt != null)
            {
                if (options.shzt == -1)
                {
                    sqlcount += " and shzt is null  ";
                    sql += " and shzt is null  ";
                }
                else if (options.shzt == 0)
                {
                    sqlcount += " and shzt='" + options.shzt + "'";
                    sql += "  and shzt='" + options.shzt + "'";
                }
                else if (options.shzt == 1)
                {
                    sqlcount += " and shzt='" + options.shzt + "'";
                    sql += " and shzt='" + options.shzt + "'";
                }
            }
            if (options.xzq != null && options.xzq.Count > 0)
            {
                if (options.xzq.Count == 3)
                {
                    string xzqdm = options.xzq[2].Split('|')[0];
                    sqlcount += " and a.xzqdm='" + xzqdm + "'  ";
                    sql += "and xzqdm='" + xzqdm + "' ";
                }
                else if (options.xzq.Count == 2)
                {
                    string citydm = options.xzq[1].Split('|')[0];
                    sqlcount += " and a.citydm='" + citydm + "'  ";
                    sql += "and citydm='" + citydm + "' ";
                }

            }
            sql += " limit @pagesize offset (@pageindex-1)*@pagesize  ";
            sqlParams.Add("pageindex", options.pageindex);
            sqlParams.Add("pagesize", options.pagesize);
            var datacount = repository.DapperContext.ExecuteScalar(sqlcount, sqlParams).GetInt();
            var data = repository.DapperContext.QueryList<zmdatarecordauditingdto>(sql, sqlParams).ToList();
            int totalPages = datacount / options.pagesize;
            if (datacount % options.pagesize != 0)
            {
                totalPages++;
            }
            return new PageGridData<zmdatarecordauditingdto> { rows = data, status = 0, total = datacount, summary = new { pagecount = totalPages } };
        }


        public WebResponseContent GetTime(string id, string xxtj_time, string t)
        {
            string sql = "update zm_data_record_auditing ";
            string colname = "";
            if (t == "xxtj_time")
            {
                colname = " set  xxtj_time = '" + xxtj_time + "'";
            }
            else if (t == "yjfk")
            {
                colname = "  set  yjfkdate = '" + xxtj_time + "' ";
            }
            else if (t == "startdate")
            {
                colname = " set  startdate = '" + xxtj_time + "'";
            }
            else if (t == "enddate")
            {
                colname = " set  enddate = '" + xxtj_time + "'";
            }
            else if (t == "xxtj_state")
            {
                colname = " set  xxtj_state = '" + xxtj_time + "'";
            }
            sql += colname + " where id = '" + id + "'";
            int count = _repository.DapperContext.ExcuteNonQuery(sql, "", null, false);

            return webResponse.OK("操作成功", new { count });
        }
        public WebResponseContent uaccepttate(string id, string acceptstate)
        {
            string sql = "update zm_data_record_auditing set accept_state='" + acceptstate + "' where id='" + id + "'";
            int count = _repository.DapperContext.ExcuteNonQuery(sql, "", null, false);

            return webResponse.OK("操作成功", new { count });
        }

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecute = (SaveModel saveModel) =>
            {
                //如果返回false,后面代码不会再执行
                return webResponse.OK();
            };
            // 在保存数据库前的操作，所有数据都验证通过了，这一步执行完就执行数据库保存
            AddOnExecuting = (zm_data_record_auditing order, object list) =>
            {
                order.shzt = 1;
                var thisdata = _repository.DapperContext.QueryList<zm_data_record>("select * from zm_data_record where  id=@id  ", new { id = order.data_id }).FirstOrDefault();
                ;
                zm_data_record_auditing lastitem = null;
                string dm = "";
                if (thisdata != null)
                {
                    if (string.IsNullOrEmpty(thisdata.xzqdm))
                    {
                        dm = thisdata.citydm;
                        lastitem = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  citydm=@dm order by sh_time desc LIMIT 1 ", new { dm = dm }).FirstOrDefault();

                    }
                    else
                    {
                        dm = thisdata.xzqdm;
                        lastitem = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  xzqdm=@dm order by sh_time desc LIMIT 1 ", new { dm = dm }).FirstOrDefault();

                    }

                }
                //数据校验
                if (lastitem == null && order.ssfa_sh_state == null)
                {
                    return webResponse.Error("实施方案审核状态不能为空");
                }
                else
                {
                    if (order.ssfa_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }

                if (lastitem == null && order.jcbg_sh_state == null)
                {
                    //if (string.IsNullOrEmpty(dm))
                    {
                        return webResponse.Error("检查报告审核状态不能为空");
                    }
                }
                else
                {
                    if (order.jcbg_sh_state == 0)
                    {
                        order.shzt = 0;
                    }

                }
                if (lastitem == null && order.zjbg_sh_state == null)
                {
                    //  if (string.IsNullOrEmpty(dm))
                    {
                        if (order.ssfa_sh_state == null)
                        {
                            return webResponse.Error("实施方案或总结报告尚未审核！");
                        }
                    }
                }
                else
                {
                    if (order.zjbg_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }

                if (lastitem == null && order.yj_szzsyxt_sh_state == null)
                {
                    //return webResponse.Error("一级：数字正射影像图审核状态不能为空");
                }
                else
                {

                    if (order.yj_szzsyxt_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.yj_jcsjcg_sh_state == null)
                {
                    //return webResponse.Error("一级：监测数据成果审核状态不能为空");
                }
                else
                {

                    if (order.yj_jcsjcg_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }
                if (lastitem == null && order.yj_scysj_sh_state == null)
                {
                    //return webResponse.Error("一级：生产元数据审核状态不能为空");
                }

                else
                {
                    if (order.yj_scysj_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.yj_sdzpsj_sh_state == null)
                {
                    //return webResponse.Error("一级：实地照片数据审核状态不能为空");
                }

                else
                {
                    if (order.yj_sdzpsj_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }

                if (lastitem == null && order.yj_wydcwj_sh_state == null)
                {
                    //return webResponse.Error("一级：外业调查文件审核状态不能为空");
                }
                else
                {
                    if (order.yj_wydcwj_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }



                if (lastitem == null && order.lj_szzsyxt_sh_state == null)
                {
                    //return webResponse.Error("两级：数字正射影像图审核状态不能为空");
                }
                else
                {
                    if (order.lj_szzsyxt_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }
                if (lastitem == null && order.lj_jcsjcg_sh_state == null)
                {
                    //return webResponse.Error("两级：监测数据成果审核状态不能为空");
                }
                else
                {

                    if (order.lj_jcsjcg_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.lj_scysj_sh_state == null)
                {
                    //return webResponse.Error("两级：生产元数据审核状态不能为空");
                }
                else
                {
                    if (order.lj_scysj_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.lj_state == null)
                {
                    //return webResponse.Error("两级：实地照片数据审核状态不能为空");
                }
                else
                {
                    if (order.lj_state == 0)
                    {
                        order.shzt = 0;
                    }
                }

                if (order.yj_state == null)
                {
                    //return webResponse.Error("两级：外业调查文件审核状态不能为空");
                }
                else
                {
                    if (order.yj_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.wydcjl_sh_state == null)
                {
                    //  if (string.IsNullOrEmpty(dm))
                    {
                        return webResponse.Error("外业调查核查记录表审核状态不能为空");
                    }
                }
                else
                {
                    if (order.wydcjl_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.jjbg_sh_state == null)
                {
                    // if (string.IsNullOrEmpty(dm))
                    {
                        return webResponse.Error("机检记录报告审核状态不能为空");
                    }
                }
                else
                {
                    if (order.jjbg_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.wth_sh_state == null)
                {
                    //   if (string.IsNullOrEmpty(dm))
                    {
                        //return webResponse.Error("委托函审核状态不能为空");
                    }
                }
                else
                {
                    if (order.wth_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }


                if (lastitem == null && order.cyd_sh_state == null)
                {
                    //  if (string.IsNullOrEmpty(dm))
                    {
                        //return webResponse.Error("抽样单审核状态不能为空");
                    }
                }
                else
                {

                    if (order.cyd_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }

                if (lastitem == null && order.chzlyy_sh_state == null)
                {
                    //  if (string.IsNullOrEmpty(dm))
                    {
                        return webResponse.Error("测绘资料交验移交清单审核状态不能为空");
                    }
                }
                else
                {
                    if (order.chzlyy_sh_state == 0)
                    {
                        order.shzt = 0;
                    }
                }

                var zm_data_record = _repository.DapperContext.QueryList<zm_data_record>("select * from zm_data_record where \"id\"=@id", new { id = order.data_id }).FirstOrDefault();
                if (zm_data_record != null)
                {
                    if (!string.IsNullOrEmpty(zm_data_record.djsjy))
                    {
                        if (order.djsjy_sh_state == null)
                        {
                            if (string.IsNullOrEmpty(dm))
                            {
                                return webResponse.Error("【地级市交验】尚未审核");
                            }
                        }
                        else
                        {
                            if (order.djsjy_sh_state == 0)
                            {
                                order.shzt = 0;
                            }

                        }
                    }
                }

                //
                //{
                //    order.shzt = 0;
                //}
                //if (order.lj_yj_state == 0)
                //{
                //    order.shzt = 0;
                //}
                var item = _repository.DapperContext.QueryList<zm_data_record>("select * from zm_data_record where \"id\"=@id", new { id = order.data_id }).FirstOrDefault();
                if (item != null)
                {
                    order.xzqdm = item.xzqdm;
                    order.xzqname = item.xzqname;
                    order.citydm = item.citydm;
                    order.citymc = item.citymc;
                    order.provcode = item.provcode;
                    order.provmc = item.provmc;
                }

                //int userid = Convert.ToInt32(thisdata.userid);
                //var sys_user = _repository.DapperContext.QueryList<Sys_User>("select * from sys_user where \"User_Id\"=@id", new { id = userid }).FirstOrDefault();
                //if (sys_user != null) 
                //{
                //    if (sys_user.Role_Id == 126)
                //    {
                //        if (order.ssfa_sh_state == 1)
                //        {
                //            order.shzt = 1;
                //        }
                //    }
                //}

                if (order.shzt == 1)
                {
                    zm_data_record_auditing recorditem = null;
                    if (!string.IsNullOrEmpty(order.xzqdm))
                    {
                        recorditem = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where xzqdm=@xzqdm and jycs is not null and shzt=1 order by jycs desc ", new { xzqdm = order.xzqdm }).FirstOrDefault();
                    }
                    else if (!string.IsNullOrEmpty(order.citydm))
                    {
                        recorditem = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where citydm=@citydm and jycs is not null and shzt=1 order by jycs desc ", new { citydm = order.citydm }).FirstOrDefault();

                    }

                    if (recorditem != null)
                    {
                        order.jycs = recorditem.jycs + 1;
                    }
                    else
                    {
                        order.jycs = 1;
                    }
                }
                order.xxtj_state = 0;
                order.accept_state = 2;
                order.sh_time = DateTime.Now;
                order.sh_name = UserContext.Current.UserTrueName;
                order.sh_id = UserContext.Current.UserId.ToString();
                return webResponse.OK();
            };
            //此方法中已开启了事务，如果在此方法中做其他数据库操作，请不要再开启事务
            // 在保存数据库后的操作，此时已进行数据提交，但未提交事务，如果返回false，则会回滚提交
            AddOnExecuted = (zm_data_record_auditing order, object list) =>
            {
                string sql = "insert into zm_message(id,xzqdm,xzqmc,citydm,citymc,provmc,provdm,data_id,isread,create_time,create_name,message)values" +
                "('" + Guid.NewGuid() + "','" + order.xzqdm + "','" + order.xzqname + "','" + order.citydm + "','" + order.citymc + "','" + order.provmc
                + "','" + order.provcode + "','" + order.id + "','0','" + DateTime.Now.ToString() + "','" + UserContext.Current.UserTrueName + "','" + order.projectname + " 已审核！') ";

                int c = _repository.DapperContext.ExcuteNonQuery(sql, "", null, false);

                return webResponse.OK("操作成功1", order.shzt);
            };


            return base.Add(saveDataModel);
        }

    }
}
